<template>
  <div>
    <el-row :gutter="20">
      <el-col
        :span="6"
        :xs="24"
      >
        <el-card
          class="box-card"
          style="margin-left: 20px; margin-top: 20px"
        >
          <div
            slot="header"
            class="clearfix"
          >
            <span>{{$t('sale_return_return_285')}}</span>
          </div>
          <el-form
            ref="checkPaidOrderForm"
            :model="checkPaidOrderForm"
            :hide-required-asterisk="true"
            size="small"
            label-width="68px"
          >
            <el-form-item
              :label="$t('sale_return_return_286')"
              prop="saleNo"
            >
              <el-input
                v-model="checkPaidOrderForm.saleNo"
                :placeholder="$t('sale_return_return_287')"
                clearable
              />
            </el-form-item>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-button
                  size="mini"
                  class="resetButton"
                  :disabled="isButtonDisabled"
                  @click="resetForm"
                >{{$t('sale_return_return_288')}}</el-button>
              </el-col>
              <el-col :span="8">
                <el-button
                  size="mini"
                  style="margin-left: -5px;"
                  class="resetButton"
                  @click="checkPaidOrderDetail"
                >{{$t('sale_return_return_289')}}</el-button>
              </el-col>
              <el-col :span="8">
                <el-button
                  size="mini"
                  style="margin-left: -10px;"
                  class="resetButton"
                  :disabled="isButtonDisabled"
                  @click="queryOtherPaidOrder"
                >{{$t('sale_return_return_290')}}</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <el-card
          class="box-card"
          style="margin-left: 20px; margin-top: 20px"
        >
          <div
            slot="header"
            class="clearfix"
          >
            <span>{{$t('sale_return_return_291')}}</span>
          </div>
          <el-form
            :hide-required-asterisk="true"
            size="small"
            label-width="68px"
          >
            <el-form-item>
              <el-button
                type="primary"
                size="small"
                style="width: 160px; margin-left: -35px;margin-bottom: 10px;"
                :disabled="isButtonDisabled"
                @click="openSalesChangeList"
              >{{$t('sale_return_return_292')}}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                size="small"
                style="width: 160px; margin-left: -35px;margin-bottom: 10px;"
                :disabled="isButtonDisabled"
                @click="openSalesReturnedList"
              >{{$t('sale_return_return_293')}}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                size="small"
                style="width: 160px; margin-left: -35px;margin-bottom: 10px;"
                :disabled="isButtonDisabled"
                @click="judgeReturnType(false)"
              >{{$t('sale_return_return_294')}}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col
        :span="18"
        :xs="24"
      >
        <el-descriptions
          border
          style="margin-top:20px; margin-right:20px;"
          :content-style="CS"
          :label-style="LS "
        >
          <el-descriptions-item
            :label="$t('sale_return_return_286')"
          >
            {{ this.saleNo }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_return_return_295')">
            {{ this.totalQuantity }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_return_return_296')">
            <el-tag
              v-if="orderInfo.payType == 1"
              type="success"
              effect="dark"
            >{{$t('sale_return_return_297')}}</el-tag>
            <el-tag
              v-if="orderInfo.payType == 2"
              effect="dark"
            >{{$t('sale_return_return_298')}}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_return_return_299')">
            {{ orderInfo.total }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_return_return_300')">
            {{ orderInfo.preferentialTotal }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('sale_return_return_301')">
            {{ orderInfo.promotionDesc }}
          </el-descriptions-item>
        </el-descriptions>
        <br>
        <el-card
          class="box-card"
          style="margin-right: 20px"
        >
          <div
            slot="header"
            class="clearfix"
          >
            <span class="card-tile-center">{{$t('sale_return_return_302')}}</span>
          </div>
          <el-table
            ref="saleItemTable"
            :data="saleItemList"
            :row-class-name="rowSaleItemIndex"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              align="center"
            />
            <el-table-column
              :label="$t('sale_return_return_303')"
              align="center"
              prop="productName"
              show-overflow-tooltip
            />
            <el-table-column
              :label="$t('sale_return_return_304')"
              align="center"
              width="170"
            >
              <template slot-scope="scope">
                <img
                  v-if="scope.row.imageUrl != null"
                  :src="scope.row.imageUrl"
                  alt="Item Image"
                  style="width: 120px; height: auto"
                >
                <span v-else>{{$t('sale_return_return_305')}}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('sale_return_return_306')"
              align="center"
              prop="price"
            />
            <el-table-column
              :label="$t('sale_return_return_307')"
              align="center"
              prop="color,size"
            >
              <template slot-scope="scope">
                [{{ scope.row.color }},{{ scope.row.size }}]
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('sale_return_return_308')"
              align="center"
              prop="quantity"
              width="100"
            />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <!-- 查找其他已完成的订单弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_return_return_309')"
      :visible.sync="checkPaidOrder"
      width="600px"
      append-to-body
    >
      <el-table
        ref="DataTable"
        border
        :data="paidOrderList"
        style="border: 1px solid rgb(211 211 211); margin-left: 20px; width: 96%"
      >
        <el-table-column
          :label="$t('sale_return_return_286')"
          align="center"
          prop="saleNo"
        />
        <el-table-column
          :label="$t('sale_return_return_300')"
          align="center"
          prop="preferentialTotal"
          width="100px"
        />
        <el-table-column
          :label="$t('sale_return_return_310')"
          align="center"
          prop="payType"
          width="100px"
        />
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_311')"
          align="center"
          prop="payTime"
          width="100px"
        />
        <el-table-column
          :label="$t('sale_return_return_312')"
          align="center"
          prop="payTime"
          width="100px"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-position"
              @click="loadPaidOrder(scope.row)"
            >{{$t('sale_return_return_289')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 商品退货弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_return_return_313')"
      :visible.sync="salesReturnedListOpen"
      width="800px"
      append-to-body
    >
      <el-table
        ref="DataTable"
        border
        :data="selectedGoodsList"
        style="border: 1px solid rgb(211 211 211); margin-left: 20px; width: 96%"
        row-key="id"
      >
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_303')"
          align="center"
          prop="productName"
          width="160"
        />
        <el-table-column
          :label="$t('sale_return_return_314')"
          align="center"
          prop="price"
          width="100"
        />
        <el-table-column
          :label="$t('sale_return_return_307')"
          align="center"
          prop="color,size"
          width="160"
        >
          <template slot-scope="scope">
            [{{ scope.row.color }},{{ scope.row.size }}]
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('sale_return_return_315')"
          align="center"
          prop="quantity"
        >
          <template v-slot="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :max="getMaxQuantity(scope.row.id)"
              @change="handleQuantityChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_312')"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="removeCheckedGoods(scope.row)"
            >{{$t('sale_return_return_316')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-form
        ref="salesReturnedForm"
        label-position="left"
        label-width="20%"
        :hide-required-asterisk="true"
        :model="salesReturnedForm"
        style="margin-left: 20px;margin-top: 15px;"
      >
        <el-form-item
          :label="$t('sale_return_return_315')"
          style="margin-bottom: 5px;"
          prop="quantity"
        >
          <span>{{ salesReturnedForm.quantity }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_return_return_317')"
          style="margin-bottom: 5px;"
          prop="amount"
        >
          <span>{{ salesReturnedForm.amount }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_return_return_318')"
          style="margin-bottom: 5px;"
          prop="type"
        >
          <span v-if="salesReturnedForm.type === 1">{{$t('sale_return_return_297')}}</span>
          <span v-if="salesReturnedForm.type === 2">{{$t('sale_return_return_298')}}</span>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          @click="salesReturnedListOpen = false"
        >{{$t('sale_return_return_319')}}</el-button>
        <el-button
          type="danger"
          @click="judgeReturnType(true)"
        >{{$t('sale_return_return_320')}}</el-button>
      </span>
    </el-dialog>
    <!-- 退货警示弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_return_return_321')"
      :visible.sync="salesReturnAlertOpen"
      width="400px"
      append-to-body
    >
      <span class="salesReturnWarning">{{$t('sale_return_return_322')}}</span>
      <el-form
        ref="salesReturnedForm"
        label-position="left"
        label-width="20%"
        :hide-required-asterisk="true"
        :model="salesReturnedForm"
        style="margin-left: 20px;margin-top: 30px;transform: translateX(15px);"
      >
        <el-form-item
          :label="$t('sale_return_return_323')"
          style="margin-bottom: 5px;"
          prop="reason"
        >
          <el-select
            v-model="refundReason"
            :placeholder="$t('sale_return_return_324')"
            clearable
            @change="handleSelectChange"
          >
            <el-option
              v-for="item in reasonOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-if="isShowInput"
            v-model="refundReason"
            :placeholder="$t('sale_return_return_325')"
            style="width: 200px;"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="salesReturnAlertOpen = false"
        >{{$t('sale_return_return_326')}}</el-button>
        <el-button
          type="danger"
          @click="confirmRefund"
        >{{$t('sale_return_return_327')}}</el-button>
      </span>
    </el-dialog>
    <!-- 售后单据弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_return_return_328')"
      :visible.sync="salesReturnedReportOpen"
      width="400px"
      append-to-body
    >
      <el-form
        ref="salesReturnedReportForm"
        label-position="left"
        label-width="20%"
        :hide-required-asterisk="true"
        :model="salesReturnedReportForm"
      >
        <el-form-item
          :label="$t('sale_return_return_329')"
          style="margin-bottom: 5px;"
          prop="refundNo"
        >
          <span>{{ salesReturnedReportForm.refundNo }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_return_return_330')"
          style="margin-bottom: 5px;"
          prop="sa1eNo"
        >
          <span>{{ salesReturnedReportForm.saleNo }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_return_return_331')"
          style="margin-bottom: 5px;"
          prop="quantity"
        >
          <span>{{ salesReturnedReportForm.quantity }}</span>
        </el-form-item>
        <el-form-item
          v-if="kind === 1"
          :label="$t('sale_return_return_317')"
          style="margin-bottom: 5px;"
          prop="amount"
        >
          <span>{{ salesReturnedReportForm.amount }}</span>
        </el-form-item>
        <el-form-item
          v-if="kind === 1"
          :label="$t('sale_return_return_318')"
          style="margin-bottom: 5px;"
          prop="type"
        >
          <span v-if="salesReturnedReportForm.type === 1">{{$t('sale_return_return_332')}}</span>
          <span v-if="salesReturnedReportForm.type === 2">{{$t('sale_return_return_333')}}</span>
        </el-form-item>
        <el-form-item
          :label="$t('sale_return_return_334')"
          style="margin-bottom: 5px;"
          prop="refundTime"
        >
          <span>{{ salesReturnedReportForm.refundTimeString }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 商品换货弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_return_return_335')"
      :visible.sync="salesChangeListOpen"
      width="800px"
      append-to-body
    >
      <h3 style="margin-left: 20px">{{$t('sale_return_return_336')}}</h3>
      <el-table
        border
        :data="beforeExchangeList"
        style="
          border: 1px solid rgb(211 211 211);
          margin-left: 20px;
          width: 96%;
        "
        row-key="id"
      >
        <el-table-column
          :label="$t('sale_return_return_337')"
          align="center"
          type="index"
          width="80"
        />
        <el-table-column
          v-if="false"
          :label="$t('sale_return_return_338')"
          align="center"
          prop="productId"
          width="160"
        />
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_303')"
          align="center"
          prop="productName"
          width="160"
        />
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_314')"
          align="center"
          prop="price"
          width="100"
        />
        <!-- <el-table-column prop="speId" type="hidden"></el-table-column> -->
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_307')"
          align="center"
          prop="color,size"
          width="120"
        >
          <template slot-scope="scope">
            [{{ scope.row.color }},{{ scope.row.size }}]
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_339')"
          align="center"
          prop="quantity"
        />
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_312')"
          align="center"
          width="140"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="removeSelectedGoods(scope.row, scope.$index)"
            >{{$t('sale_return_return_316')}}</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="clickChange(scope.$index, scope.row)"
            >{{$t('sale_return_return_340')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <h3 style="margin-left: 20px">{{$t('sale_return_return_341')}}</h3>
      <el-table
        ref="exchangeList"
        :data="exchangeList"
        border
        style="
          border: 1px solid rgb(211 211 211);
          margin-left: 20px;
          width: 96%;
        "
        row-key="id"
      >
        <el-table-column
          :label="$t('sale_return_return_337')"
          align="center"
          type="index"
          width="50"
        />
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_303')"
          align="center"
          prop="productName"
          width="160"
        />
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_314')"
          align="center"
          prop="price"
          width="100"
        />
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_307')"
          align="center"
          prop="color,size"
          width="160"
        >
          <template slot-scope="scope">
            [{{ scope.row.color }},{{ scope.row.size }}]
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_339')"
          align="center"
          prop="quantity"
        />
        <el-table-column
          show-overflow-tooltip
          :label="$t('sale_return_return_312')"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="removeRealSelectedGoods(scope.row, scope.$index)"
            >{{$t('sale_return_return_316')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-form
        ref="salesReturnedForm"
        label-position="left"
        label-width="20%"
        :hide-required-asterisk="true"
        :model="salesReturnedForm"
        style="margin-left: 20px; margin-top: 15px"
      >
        <el-form-item
          :label="$t('sale_return_return_342')"
          style="margin-bottom: 5px"
          prop="reason"
        >
          <el-select
            v-model="changeReason"
            :placeholder="$t('sale_return_return_324')"
            clearable
            @change="handleSelectChange"
          >
            <el-option
              v-for="item in reasonOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-if="isShowInput"
            v-model="changeReason"
            :placeholder="$t('sale_return_return_343')"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="salesChangeListOpen = false">{{$t('sale_return_return_319')}}</el-button>
        <el-button
          type="danger"
          @click="openConfirmChange"
        >{{$t('sale_return_return_344')}}</el-button>
      </span>
    </el-dialog>
    <!-- 更换商品输入框，默认不显示-->
    <el-dialog
      :visible.sync="clickChangeButton"
      append-to-body
      :title="$t('sale_return_return_345')"
      width="330px"
      style="margin-right: 10px; margin-top: 10px"
    >
      <div
        slot="header"
        class="clearfix"
      >
        <span>{{$t('sale_return_return_345')}}</span>
      </div>
      <el-form
        ref="changeItemForm"
        :model="changeItemForm"
        :rules="changeItemRules"
        :hide-required-asterisk="true"
        size="small"
        label-width="68px"
      >
        <el-form-item
          :label="$t('sale_return_return_303')"
          prop="productName"
        >
          <el-input
            v-model="currentProductName"
            :disabled="true"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item
          :label="$t('sale_return_return_346')"
          prop="speId"
        >
          <el-select
            v-model="changeItemForm.speId"
            :placeholder="$t('sale_return_return_324')"
            style="width: 200px;"
            @change="handleSpecChange"
          >
            <el-option
              v-for="item in specificationOptions"
              :key="item.id"
              :label="item.color + ',' + item.size"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          :label="$t('sale_return_return_347')"
          prop="quantity"
        >
          <template>
            <el-input-number
              v-model="changeItemForm.quantity"
              style="width: 200px"
              :min="1"
              :max="currentLimitQuantity"
            />
          </template>
        </el-form-item>
        <el-row :gutter="10">
          <el-button
            size="mini"
            class="changeItemButton"
            style="margin-left: 100px; width: 80px; height: 30px"
            @click="enterExchangeItem"
          >{{$t('sale_return_return_348')}}</el-button>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 更换商品警示弹窗，默认不显示 -->
    <el-dialog
      :title="$t('sale_return_return_349')"
      :visible.sync="salesChangeAlertOpen"
      width="400px"
      append-to-body
    >
      <span class="salesChangeWarning">{{$t('sale_return_return_322')}}</span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="salesChangeAlertOpen = false"
        >{{$t('sale_return_return_326')}}</el-button>
        <el-button
          type="danger"
          @click="confirmChange"
        >{{$t('sale_return_return_327')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPaidOrderDeatil
} from "@/api/cash";
import {
  getOrderList,
} from "@/api/order";
import {
  getlistByProductId
} from "@/api/specification";
import {
  getProduct
} from "@/api/product";
import {
  openPartialReturn,
  modifyQuantityOfItems,
  removeReturnedItem,
  confirmPartialReturn,
  confirmFullReturn,
  getRefundOrderNote
} from "@/api/refund";
import {
  getInitExchangeList,
  removeBeforeExchangeItem,
  addExchangeItem,
  removeAfterExchangeItem,
  confirmExchange,
} from "@/api/exchange";
export default {
  name: "Return",
  // 定义属性
  data() {
    return {
      CS: {
        'min-width': '150px',   //最小宽度
      },
      LS:{
        'text-align': 'center',  //文本居中
        'min-width': '100px',   //最小宽度
      },
      // 选中数组
      saleItemIds: [],
      //展示栏数据
      orderInfo: {
      },
      // 根据订单号查询订单表单
      checkPaidOrderForm: {
        saleNo: "",
      },
      // 订单号
      saleNo:'',
      // 订单商品总件数
      totalQuantity: "",
      // 退货原因
      refundReason: "",
      // 当前选中的退货原因
      selectedReason: "",
      // 查询订单的表格展示数据
      saleItemList: [],
      // 其他已支付订单的表格展示数据
      paidOrderList: [],
      // 需要退换的商品（退换清单）
      selectedGoodsList: [],
      // 退货清单的数据展示表单
      salesReturnedForm: [],
      // 退换单据的表格展示数据
      salesReturnedReportForm: [],
      // 是否显示“查看其他已支付订单”弹窗
      checkPaidOrder: false,
      // 是否显示“退货清单”弹窗
      salesReturnedListOpen: false,
      // 是否显示“退换警示”弹窗
      salesReturnAlertOpen: false,
      // 是否显示“退换单据”弹窗
      salesReturnedReportOpen: false,
      // 退款原因输出框（其他）
      isShowInput: false,
      // 退款原因下拉框选项数据
      reasonOptions: [
        {
          value: 1,
          label: this.$t('sale_return_return_350'),
        },
        {
          value: 2,
          label: this.$t('sale_return_return_351'),
        },
        {
          value: 3,
          label: this.$t('sale_return_return_352'),
        },
        {
          value: 4,
          label: this.$t('sale_return_return_353'),
        },
      ],
      kind:null,
      // 是否部分退货
      isPartialRefund: false,
      // 初始状态，按钮不禁用
      isButtonDisabled: false,
      ////////////////////////换货业务
      // 是否显示“换货清单”弹窗
      salesChangeListOpen: false,
      // 换货中，存储点击的那一行的原销售项id
      currentOriItemId: null,
      //换货原因
      changeReason: "",
      // 换商品警示弹窗是否显示
      salesChangeAlertOpen: false,
      // 是否弹出“商品输入”弹窗
      clickChangeButton: false,
      // 选中的待换货商品集合
      selectedExchangeList: [],
      // 换货弹窗中待换货商品集合
      beforeExchangeList: [],
      // 换货弹窗中换货后的待换货商品集合
      operateExchangeList: [],
      // 换货弹窗中换货商品集合
      exchangeList: [],
      // 当前选中的商品SN
      currentProductName: "",
      // 换货产品的索引
      exchangeIndex: 0,
      // 产品规格清单
      specificationOptions: [],
      // 产品更换表单
      changeItemForm: {
        speId:null,
        productName: "",
        quantity: 1,
        color: "",
        size: "",
        oriItem: {
          productId: "",
          status: "",
          imageUrl: "",
          saleId: "",
        },
        oriItemId: null,
      },
      // 商品换货录入临时最大值
      currentLimitQuantity:null,
      // 商品退货临时最大值
      currentReturnLimitQuantity:null,
      // 换货小票
      salesChangeReportForm: {},
      // 产品移除更换表单
      removeItemForm: {
        oriItemId: null,
        removeItem: null,
      },
      // 产品移除更换表单
      afterRemoveItemForm: {
        oriItemId: null,
        removeItem: null,
      },
      // 表单校验
      changeItemRules: {
        // speId: [{ required: true, message: "商品规格不能为空" }],
        quantity: [{ required: true, message: this.$t('sale_return_return_354') }],
      },
    };
  },
  watch: {
    'salesReturnedForm.reason': {
      handler(newVal) {
        // 检查 newVal 是否在 reasonOptions 中，并且其值是否为 4
        this.isShowInput = this.reasonOptions.some(item => item.value === newVal && newVal === 4);
      },
      // 使用 immediate: true 使得在组件加载时立即执行一次 handler
      immediate: true,
    },
  },
  // 方法集合
  methods: {
    // 获取查询的已支付订单的信息
    checkPaidOrderDetail() {
      if(this.checkPaidOrderForm.saleNo =="" || this.checkPaidOrderForm.saleNo == null){
        this.$message.error(this.$t('sale_return_return_355'));
      }else {
        getPaidOrderDeatil(this.checkPaidOrderForm.saleNo).then((response) => {
          this.saleNo = this.checkPaidOrderForm.saleNo;
          this.orderInfo = response.data;
          this.changeItemForm.oriItem.saleId = this.orderInfo.id;
          // console.log(this.changeItemForm.saleId);
          this.saleItemList = this.orderInfo.saleItemList;
          this.totalQuantity = this.orderInfo.quantity;
          this.isButtonDisabled=false

        })
      }
    },
    // 重置查询已支付订单的表单
    resetForm() {
      this.checkPaidOrderForm.saleNo = "";
    },
    // 查询其他已支付的订单
    queryOtherPaidOrder() {
      this.checkPaidOrder = true;
      const queryparams = {
        status: "3"
      }
      getOrderList(queryparams).then((response) => {
        this.paidOrderList = response.data.records;
        this.paidOrderList.forEach(item => {
          item.payTime = this.formatTime(item.payTime)
        })
        // console.log(this.paidOrderList);
      })
    },
    // 加载已支付的订单
    loadPaidOrder(row) {
      getPaidOrderDeatil(row.saleNo).then((response) => {
        this.saleNo = row.saleNo;
        this.orderInfo = response.data;
        this.changeItemForm.oriItem.saleId = this.orderInfo.id;
        this.saleItemList = this.orderInfo.saleItemList;
        this.totalQuantity = this.orderInfo.quantity;
        setTimeout(() => {
          this.checkPaidOrder = false;
        }, 500);
      })
    },
    // 修改时间格式
    formatTime(date) {
      var dateee = new Date(date).toJSON();
      return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.saleItemIds = selection.map((item) => item.id)
      this.selectedExchangeList = selection;//页面选中的待换货商品集合
      this.beforeExchangeList = selection.map((item) => ({
        id: item.id,
        productId: Number(item.productId),
        productName: item.productName,
        color: item.color,
        size: item.size,
        quantity: item.quantity,
        price: item.price,
        speId: item.speId,
        saleId:item.saleId,
        imageUrl:item.imageUrl,
        status:item.status
      }));
    },
    // 打开退货清单界面
    openSalesReturnedList() {
      if(this.saleNo == null || this.saleNo ==""){
        this.$message.error(this.$t('sale_return_return_356'));
      }else {
        if(this.saleItemIds.length==0) {
          this.$message.error(this.$t('sale_return_return_357'));
        }else {
          this.salesReturnedListOpen = true;
          this.getSelectedGoods();
        }
      }

    },
    getMaxQuantity(id) {
      // 根据 productId 查找最大退货数量
      const maxQuantity = this.saleItemList.find(item => item.id === id)?.quantity || 999;
      return maxQuantity;
    },
    // 查询已勾选的需要退货的商品
    getSelectedGoods() {
      const saleReturnedData = {
        saleItemIds: this.saleItemIds,
        saleNo: this.saleNo,
      }
      // console.log(saleReturnedData);
      openPartialReturn(saleReturnedData).then((response) => {
        this.selectedGoodsList = response.data.saleItems;
        this.salesReturnedForm = response.data
      })
    },
    // 退换货原因选项改变事件
    handleSelectChange(value) {
      const selectedOption = this.reasonOptions.find(option => option.value === value);
      if (selectedOption) {
        this.refundReason = selectedOption.label;
        this.changeReason = selectedOption.label;
        this.isShowInput = false; // 隐藏 el-input
        if (selectedOption.value === 4) {
          this.isShowInput = true;
        }
      } else {
        this.refundReason = '';
        this.changeReason = '';
        this.isShowInput = false;
      }
    },
    // 修改退货件数
    handleQuantityChange(row) {
      const editQuantityparams = {
        quantity: row.quantity,
        saleItemId: row.id,
      }
      modifyQuantityOfItems(editQuantityparams).then((response) => {
        // console.log(response.data);
        this.selectedGoodsList = response.data.saleItems;
        this.salesReturnedForm = response.data
      })
    },
    // 移除已勾选的商品
    removeCheckedGoods(row) {
      removeReturnedItem(row.id).then((response) => {
        // console.log(response.data);
        this.$message.success(this.$t('sale_return_return_358'));
        this.selectedGoodsList = response.data.saleItems;
        this.salesReturnedForm = response.data
      }).catch(() => {
        this.$message.error(this.$t('sale_return_return_359'));
      })
    },
    // 判断退货类型
    judgeReturnType(isPartial) {
      this.isPartialRefund = isPartial;
      if(this.isPartialRefund == false) {
        if(this.saleNo == null || this.saleNo ==""){
          this.$message.error(this.$t('sale_return_return_356'));
        }else {
          this.salesReturnAlertOpen = true;
        }
      }else {
        this.salesReturnAlertOpen = true;
      }
    },
    // 确认退货退款
    confirmRefund() {
      if(this.isPartialRefund) {
        this.handlePartialRefund();
      }else {
        this.handleFullRefund();
      }
    },
    // 部分退货
    handlePartialRefund() {
      // console.log('部分退货');
      const refundparams = {
        reason: this.refundReason,
        saleNo: this.saleNo,
      }
      confirmPartialReturn(refundparams).then(() => {
        this.getRefundOrderNote();
      })
    },
    // 全单退货
    handleFullRefund() {
      // console.log(this.$t('sale_return_return_294'));
      const refundparams = {
        reason: this.refundReason,
        saleNo: this.saleNo,
      }
      confirmFullReturn(refundparams).then(() => {
        this.getRefundOrderNote();
      })
    },
    // 查找退货单据
    getRefundOrderNote() {
      getRefundOrderNote(this.saleNo).then((response) => {
        this.salesReturnedReportForm = response.data;
        this.kind = this.salesReturnedReportForm.kind;
        // console.log(this.salesReturnedReportForm);
        this.$message.success(this.$t('sale_return_return_360'));
        this.toggleButton();
        this.$refs.saleItemTable.clearSelection();
        this.salesReturnAlertOpen = false;
        this.salesReturnedListOpen = false;
        setTimeout(() => {
          this.salesReturnedReportOpen = true;
        }, 300)
      })
    },
    // 切换按钮禁用状态
    toggleButton() {
      this.isButtonDisabled = !this.isButtonDisabled;
    },
    /////////////////////////////换货业务
    // 打开换货清单界面
    openSalesChangeList() {
      if(this.saleNo == null || this.saleNo ==""){
        this.$message.error(this.$t('sale_return_return_356'));
      }else {
        if (this.saleItemIds.length == 0) {
          this.$message.error(this.$t('sale_return_return_361'));
        }else {
          this.getInitExchangeList();
        }
      }
    },
    // 获取待换货清单
    getInitExchangeList() {
      getInitExchangeList(this.selectedExchangeList).then((response) => {
        if (response.data) {
          // 打开换货弹窗
          this.salesChangeListOpen = true;
        } else this.$message.error(this.$t('sale_return_return_362'));
      });
    },
    // 更改此货物，上表的更换按钮
    clickChange(index, row) {
      this.exchangeIndex = index;
      // this.changeItemForm.speId=Number(row.speId)// 设置默认规格
      this.currentLimitQuantity=row.quantity// 设置可换货最大值
      // 判断此货物是否已经达到换货上限
      // console.log(index);
      this.clickChangeButton = true;
      this.currentProductName = row.productName;
      this.changeItemForm.oriItem = row;
      // 存储点击的这一行原始销售项ID，用于点击商品更换的确认按钮提交oriItemId
      this.currentOriItemId = Number(row.id);
      this.changeItemForm.oriItem.productId = Number(row.productId);
      getProduct(this.changeItemForm.oriItem.productId).then((response) => {
        this.changeItemForm.oriItem.imageUrl = response.data.imageUrl;
      })
      // console.log(this.changeItemForm);
      // 搜索出该商品的产品规格
      getlistByProductId(Number(row.productId)).then((response) => {
        this.specificationOptions = response.data;
      });
      // 默认选中这个规格
      this.changeItemForm.speId=row.speId
    },
    // 移除上表待更换此货物
    removeSelectedGoods(row, $index) {
      // console.log($index);
      // console.log(row.id);
      removeBeforeExchangeItem(row.id).then((response) => {
          // console.log($index);
          // console.log(this.beforeExchangeList);
          this.beforeExchangeList.splice($index, 1);
          this.$message.success(response.data);
        })
        .catch(() => {
          this.$message.error(this.$t('sale_return_return_359'));
        });
    },
    // 移除下表更换后此货物
    removeRealSelectedGoods(row, $index) {
      this.afterRemoveItemForm.oriItemId = Number(row.oriItemId);
      this.afterRemoveItemForm.removeItem = row;
      // console.log(this.afterRemoveItemForm)
      removeAfterExchangeItem(this.afterRemoveItemForm).then((response) => {
          // 在上表中查找该条记录的oriItemId
          let findItem=this.beforeExchangeList.find(item => Number(item.id) === Number(row.oriItemId))
          if(findItem){
            findItem.quantity+=row.quantity
          }
          else{
            // 把原来的加回来，在saleItemList里面找这条数据项，push进去
            let findOriItem=this.saleItemList.find(item => Number(item.id) === Number(row.oriItemId))
            if(findOriItem)
              this.beforeExchangeList.push(findOriItem);
            // console.log(this.beforeExchangeList)
          }
          this.exchangeList.splice($index, 1);
          this.$message.success(response.data);
        })
        .catch(() => {
          this.$message.error(this.$t('sale_return_return_359'));
        });
    },
    // 规范化changeItemForm以便传入后端
    handleSpecChange(speId) {
      const selectedSpec = this.specificationOptions.find(
        (item) => item.id === speId
      );
      this.changeItemForm.color = selectedSpec.color;
      this.changeItemForm.size = selectedSpec.size;
      // this.changeItemForm.speId = Number(speId);
    },
    // "更换货物"弹窗的确定按钮,这里正式访问后端
    enterExchangeItem() {
      // console.log(this.beforeExchangeList);
      // console.log(this.currentOriItemId);
      this.changeItemForm.oriItemId = this.currentOriItemId;
      this.changeItemForm.oriItem.status = 6;
      console.log(this.changeItemForm);
      addExchangeItem(this.changeItemForm).then((response) => {
        if (response.data != null) {
          // 调整插入表格的内容
          const newDataItem = {
            ...response.data, // 使用扩展运算符合并后端数据
            oriItemId: this.currentOriItemId, // 添加该商品的oriItemId
          };
          // console.log(this.exchangeList)
          // 查找exchangeList里面是否有该记录
          if (this.exchangeList.length > 0) {
            // 如果这个list里面有东西，那要找找是不是之前已经换过一次这个商品，且上次换的和这次换的一样
            const existingItem = this.exchangeList.find((item) =>
                item.productName === this.changeItemForm.oriItem.productName &&
                Number(item.speId) === this.changeItemForm.speId
            );
            //如果存在这一行，就把这一行删掉，再push新的
            if (typeof existingItem !== "undefined") {
              const index = this.exchangeList.indexOf(existingItem); // 获取现有记录的索引
              this.exchangeList.splice(index, 1); // 删除现有记录
            }
            //如果不存在这一行，直接push新的
            else{
              // console.log(111)
              this.exchangeList.push(newDataItem);
              this.clickChangeButton = false;
            }
          }
          else{
            // console.log(111)
            // 如果这个list里面没有东西，那直接插入就好，不用查找
            this.exchangeList.push(newDataItem);
          }
          this.clickChangeButton = false;
        } else {
          this.$message.error(this.$t('sale_return_return_363'));
          this.clickChangeButton = false;
        }
      // 更新待换货清单
      this.updateBeforeExchangeList();
      // 清空数据
      this.clearChangeItemForm();
      });
    },
    // 更新待换货清单
    updateBeforeExchangeList() {
      // 更新待换货清单
      let judgeQuantity = this.beforeExchangeList[this.exchangeIndex].quantity
      judgeQuantity -= this.changeItemForm.quantity;
      this.beforeExchangeList[this.exchangeIndex].quantity = judgeQuantity;
      if(judgeQuantity <= 0) {
        this.beforeExchangeList.splice(this.exchangeIndex, 1)
      }
    },
    // 点击确定换货，判断是否可以换货，弹出警示窗
    openConfirmChange() {
      this.salesChangeAlertOpen = true;
    },
    // 确定换货
    confirmChange() {
      confirmExchange(this.changeReason,this.saleNo).then((response) => {
        // console.log(response.data)
        // console.log(this.saleNo);
        this.kind = response.data.kind;
        // console.log(this.kind);
        this.salesReturnedReportForm = response.data;
        // console.log(this.salesReturnedReportForm);
        this.$message.success(this.$t('sale_return_return_364'));
        this.toggleButton();
        this.$refs.saleItemTable.clearSelection();
        this.salesChangeAlertOpen = false;
        this.salesChangeListOpen = false;
        this.checkPaidOrderForm.saleNo = "";
        setTimeout(() => {
          this.salesReturnedReportOpen = true;
        }, 300)
      }).catch(() => {
        this.$message.error(this.$t('sale_return_return_365'));
      })
    },
    // 清空换货商品输入框数据
    clearChangeItemForm(){
      // this.changeItemForm={}
      this.changeItemForm.quantity=1;
    },
    //为table订单明细添加序号
    rowSaleItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
  },
};
</script>

<style>
.card-tile-center {
  display: flex;
  justify-content:center;
  align-items:center;
}
.resetButton,
.resetButton:hover {
  background-color: #edf8f6;
}
.resetButton:hover {
  background-color: #b3cec9;
  color: white;
}
.salesReturnWarning {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  font-weight: 700;
}
</style>
